import numpy as np


# 获取样本均值
def get_avg(x):
    return np.mean(x, axis=0)


# 求类内离散度Si
def get_Si(x, x_mean):
    x_mean = x_mean.reshape(x.shape[1], 1)
    Si = np.zeros((x.shape[1], x.shape[1]))
    for xi in x:
        temp_xi = xi.copy().reshape(x.shape[1], 1)
        temp = (temp_xi - x_mean)
        Si = Si + np.dot(temp, temp.T)
    return Si


# 求法向量w
def get_w(x1_mean, x2_mean, Sw):
    return np.dot(np.linalg.inv(Sw), (x1_mean - x2_mean))


# 获取分类阈值b和法向量w
def get_b_w(x1, x2):
    x1_mean = get_avg(x1)
    x2_mean = get_avg(x2)
    S1 = get_Si(x1, x1_mean)
    S2 = get_Si(x2, x2_mean)
    Sw = S1 + S2
    w = get_w(x1_mean, x2_mean, Sw)

    # 选取分类阈值b
    b = np.dot(w.T, (x1_mean + x2_mean)) / 2

    return b, w


def fisher(x1, x2, x_test):
    b, w = get_b_w(x1, x2)
    y_test = np.dot(w.T, x_test)
    if y_test > b:
        return True
    else:
        return False


